package cn.jslfl.sample.webserver;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
 
public class Processor extends Thread {
	private Socket socket;
	private InputStream serverIn;
	private PrintStream serverOut;
	public static final String WEB_ROOT;
	static{
		String binRoot = Processor.class.getResource("/").getFile().toString();
		WEB_ROOT = binRoot.split("/bin")[0] + "/webapps";
	}
	public Processor(Socket socket){
		this.socket = socket;
		try {
			serverIn = this.socket.getInputStream();
			serverOut = new PrintStream(this.socket.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	public void run(){
		String fileName = parse(serverIn);
		sendResponse(fileName);
	}
	
	private String parse(InputStream in){
		BufferedReader br = new BufferedReader(new InputStreamReader(serverIn));
		try {
			String httpMsg = br.readLine();
			
			System.out.println(httpMsg);//TODO del...
			
			String[] httpContent = httpMsg.split(" ");
			if(httpContent.length != 3){
				sendErrorMessage(400, "Request Error!");
				return null;
			}
			
			return httpContent[1];
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return null;
	}
	
	private void sendErrorMessage(int errorCode, String errorMsg){
		serverOut.println("HTTP/1.0 " + errorCode + " " + errorMsg);
		serverOut.println("content-type: text/html");
		serverOut.println();
		serverOut.println("<html><head><title>" +
				errorCode + " " + errorMsg +
				"</title></head><body><h1>" +
				errorCode + ", " + errorMsg +
				"</h1></body></html>");
		
		serverOut.flush();
		serverOut.close();
		try {
			serverIn.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	private void sendResponse(String fileName){
		if(fileName == null || "".equals(fileName)){
			sendErrorMessage(404, "File Not Found!");
		}
		
		System.out.println(WEB_ROOT + fileName);//TODO del....
		
		File file = new File(WEB_ROOT + fileName);
		if(!file.exists()){
			sendErrorMessage(404, "File Not Found!");
			return;
		}
		InputStream fileIn = null;
		try {
			fileIn = new FileInputStream(file);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		byte[] fileContent = new byte[(int)file.length()];
		try {
			fileIn.read(fileContent);
			serverOut.println("HTTP/1.0 200 requesetFile");
			serverOut.println("content-lenth:" + fileContent.length);
			serverOut.println();
			serverOut.write(fileContent);
			serverOut.flush();
			serverOut.close();
			fileIn.close();
			serverIn.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
		
}
